import AuthComponent from '@/components/Authorized/AuthComponent';
import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Menu, message, Modal, Select } from 'antd';
import React, { useState, useRef, useCallback, useEffect } from 'react';
import { useRequest } from '@umijs/hooks';
import ProTable from '@ant-design/pro-table';
import { useActivate } from 'react-activation';

import CreateForm from './components/CreateForm';
import AddPort from './components/AddPort';
import UpdateForm from './components/UpdateForm';
import { queryCityInfo, querySites, getRuleTable, saveDataRule, deleteRule, saveDataSites, getVipRoomBy3Code} from '../../service.js';
import styles from './index.less';
import { controlTableHeight } from '@/utils/pagesGeneralMethods'; // 页面通用方法

const { confirm } = Modal

const VipRoomRule = () => {

  const [selectSites, setSelectSites] = useState([]) //站点下拉框
  const [selectVipRoomData, setSelectViproomData] = useState([]) //贵宾室下拉框
  const {run: getSitesData} = useRequest(querySites,{
    loadingDelay: true,
    onSuccess: res => {
      let temp = res.split(',')
      setSelectSites(temp)
    }
  }); //获取站点

  const {run: getVipRoom} = useRequest((value)=>getVipRoomBy3Code({airpId: value}),{
    manual: true,
    onSuccess: res => {
      setSelectViproomData(res.data)
    }
  }); //获取贵宾室下拉框
  const [portCode, setPortCode] = useState('') // 保存航站的值
  useEffect(()=>{
    getSitesData()
    getVipRoom()
  },[])

  useActivate(() => {
    getVipRoom()
    getSitesData()
  })

  const [createModalVisible, handleCreateModalVisible] = useState(false); // 新建规则
  const [portModalVisible, handlePortModalVisible] = useState(false); // 新建站点
  const [updateModalVisible, handleUpdateModalVisible] = useState(false); // 编辑规则
  const [updateData, saveUpdateData] = useState({})

  const [selectedRowKeys, handleSelectedRowKeys] = useState([]) // 勾选索引
  const [selectedRows, handleSelectedRows] = useState([]) // 勾选列
  const actionRef = useRef();

  const [isCollapse, controlC] = useState(true); //搜索面板是否折叠
  const height = document.body.clientHeight - 286.5; // 表格高度自适应

  const columns = [
    {
      title: '贵宾室名称',
      dataIndex: 'name',
      width: 160,
    },
    {
      title: '容纳人数',
      dataIndex: 'capacity',
      width:120
    },
    {
      title: '可售人数',
      dataIndex: 'sellNum',
      width: 200,
    },
    {
      title: '就近登机口',
      dataIndex: 'gates',
      width: 180
    },
  ];

  // 新增站点
  const handlePort = async fields => {
    const hide = message.loading('正在添加');
    try {
      let res = await saveDataSites({...fields});
      if (res.code === '0') {
        hide();
        message.success('添加成功');
        return true
      } else {
        hide()
      }
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
      return false;
    }
  };

  // 新增保存
  const handleAdd = async fields => {
    const hide = message.loading('正在添加');
    try {
      let res = await saveDataRule({...fields, gates: fields.gates.join(','), portCode: portCode});
      if (res.code === '0') {
        hide();
        message.success('添加成功');
        return true
      } else {
        hide()
      }
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
      return false;
    }
  };

  // 编辑保存
  const handleUpdate = async fields => {
    const hide = message.loading('正在更新');
    try {
      let res = await saveDataRule({
        ...fields,
        gates: fields.gates.join(','),
      });
      if (res.code === '0') {
        hide();
        message.success('更新成功');
        return true
      } else {
        hide()
      }
    } catch (error) {
      hide();
      message.error('更新失败请重试！');
      return false;
    }
  };

  // 删除
  const handleOnOff = async (selectedRows) => {
      try {
        await deleteRule({
          id: selectedRows.map(row => row.id).toString(),
        });
        message.success(`删除成功，即将刷新`);
        return true;
      } catch (error) {
        message.error(`删除失败，请重试`);
        return false;
      }
  };

  const tableSelectChange = (selectedRowKeys, selectedRows) =>{
    handleSelectedRowKeys(selectedRowKeys)
    handleSelectedRows(selectedRows)
  }

  const rowSelection = {
    selectedRowKeys,
    onChange: tableSelectChange
  };

  return (
    <div>
      <ProTable
        headerTitle={
          <>
            <span style={{ paddingRight: 10, fontWeight: "bold", color: "#000" }}>贵宾室规则维护</span>
              航站：
              <Select
                style={{width: 120, marginRight: '10px'}}
                allowClear={true}
                showSearch
                placeholder="请选择"
                defaultActiveFirstOption={false}
                filterOption={true}
                optionFilterProp="children"
                notFoundContent={null}
                value={portCode}
                onChange={value => {
                  setPortCode(value)
                  getVipRoom(value)
                  handleSelectedRows([])
                  handleSelectedRowKeys([])
                  actionRef.current.reload();
                }}
              >
              <Select.Option key='' value=''>全部</Select.Option>
              {selectSites && selectSites.length > 0 && 
                selectSites.map((v, i) => {
                  return (
                    <Select.Option key={v.split('-')[1]} value={v.split('-')[1]}>{v}</Select.Option>
                  )
                })
              }
            </Select>
             <AuthComponent authCode="mkt.vipPriceMaintain.rule.addsites">
              <Button type='primary' onClick={() => handlePortModalVisible(true)}>添加站点</Button>
             </AuthComponent>
          </>
        }
        
        className={ `${styles.vipRoomRuleTable} rest-pro-table-form-compact`}
        actionRef={actionRef}
        options={{density: false,fullScreen:true, reload:false, setting:true}}
        rowKey="id"
        size='small'
        scroll={{y: controlTableHeight(isCollapse, 360, 470) }}
        toolBarRender={(action, { selectedRows }) => [
          <AuthComponent authCode="mkt.vipPriceMaintain.rule.save">
          <Button icon='plus' type="primary" onClick={() => {
            if (!portCode) {
              message.info('请选择站点再添加')
            } else {
              handleCreateModalVisible(true)
            }
          }}>
            新建
          </Button>
          </AuthComponent>,
          <AuthComponent authCode="mkt.vipPriceMaintain.rule.save">
          <Button icon='edit' onClick={() => {
            if (selectedRowKeys.length > 1) {
              message.error('只能选择一条进行编辑')
            } else if (selectedRowKeys.length === 0) {
              message.error('请选择编辑的条目')
            } else {
              saveUpdateData(selectedRows[0])
              handleUpdateModalVisible(true)
            }
            }}>
            编辑
          </Button>
          </AuthComponent>,
          <AuthComponent authCode="mkt.vipPriceMaintain.rule.delete">
          <Button
            icon="delete"
            onClick={ () => {
              if (selectedRowKeys.length === 0) {
                message.error("请选择删除的条目")
              } else {
                confirm({
                  title: '提示',
                  content: '确认操作后该贵宾室规则将被删除，你还要继续吗？',
                  onOk: async () => {
                    let res = await handleOnOff(selectedRows)
                    if (res) {
                      actionRef.current.reload();
                      handleSelectedRows([])
                      handleSelectedRowKeys([])
                    }
                  }
                })
              }
            }}
          >
            删除
          </Button>
          </AuthComponent>
        ]}
        search={{
          onCollapse:val => {
            controlC(val);
            // if (!val && hiddenData) {
            //   ref.current.setFieldsValue({
            //     flightNumber: hiddenData.flightNumber,
            //     org: hiddenData.org,
            //     dst: hiddenData.dst,
            //     compensateType: hiddenData.compensateType
            //   })
            // } else {
            //   hiddenData = ref.current.getFieldsValue()
            // }
          },
          span: { //设置排列方式
            xs: 24,
            sm: 24,
            md: 6,
            lg: 6,
            xl: 6,
            xxl: 6,
          }
        }}
        rowSelection={rowSelection}
        tableAlertRender={() => {
          return false;
        }}
        pagination={{
          showSizeChanger: true,
          showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 项`
        }}
        request={params => {
          return getRuleTable({portCode, ...params})
        }}
        columns={columns}
      />
      <AddPort
        onSubmit={async value => {
          const success = await handlePort(value);
          if (success) {
            handlePortModalVisible(false);
            if (actionRef.current) {
              // actionRef.current.reload();
              getSitesData()
            }
          }
        }}
        onCancel={() => handlePortModalVisible(false)}
        portModalVisible={portModalVisible}
      />
      <CreateForm
        selectVipRoomData={selectVipRoomData}
        onSubmit={async value => {
          const success = await handleAdd(value);
          if (success) {
            handleCreateModalVisible(false);
            handleSelectedRows([])
            handleSelectedRowKeys([])
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => handleCreateModalVisible(false)}
        createModalVisible={createModalVisible}
      />

      <UpdateForm
        onSubmit={async value => {
          const success = await handleUpdate(value);
          if (success) {
            handleUpdateModalVisible(false);
            handleSelectedRows([])
            handleSelectedRowKeys([])
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => handleUpdateModalVisible(false)}
        updateModalVisible={updateModalVisible}
        updateData={updateData}
      />
    </div>
  );
};

export default (VipRoomRule);
